<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './tenant.data';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { addTenantApi, updateTenantApi, getTenantInfoApi } from '/@/api/admin/tenant';

  export default defineComponent({
    name: 'TenantModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let updateInfo = {};
      const { createMessage } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 120,
        baseColProps: { lg: 11, md: 23 },
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });

        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          const res = await getTenantInfoApi(data?.record.id as string);
          updateInfo = res;
          setFieldsValue({
            ...res,
          });
        }
        updateSchema({ field: 'code', dynamicDisabled: unref(isUpdate) });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          // 暂定传递固定套餐menuId
          const params = Object.assign({ menuId: '1' }, updateInfo, values);
          const apiFn = unref(isUpdate) ? updateTenantApi : addTenantApi;
          await apiFn(params);
          // updateTenant
          closeModal();
          createMessage.success('操作成功');
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
        // treeData,
      };
    },
  });
</script>
